﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Practices.Unity;
using Sern.Abstracts.Common;
using Sern.Abstracts.Tracker.DataContracts;
using Sern.Common;
using Sern.ServiceImplementation;
using Sern.ServiceImplementation.MapReduce;
using NetServiceHost = System.ServiceModel.ServiceHost;

namespace Sern.ServiceHost.MapReduce
{
    public static class MapReduceHostFactory
    {
        
        /// <summary>
        //// In Azure for example, these addresses must be configurable by the run time environment. Hence you need the uri so that we get the port, hostname that the service is allowed to bind to.
        /// </summary>
        /// <param name="uri"></param>
        /// <returns></returns>
        public static IDisposable OpenListener(MapReduceConfiguration configuration)
        {
            var bindingScheme = ComponentLocator.Unity.Resolve<IBindingFactory>()[ClientType.MapReduceHost]();
            var host = new NetServiceHost(new MapReduceHostService(configuration.HostName),bindingScheme.GetBaseUri(configuration.HostName));

            host.AddServiceEndpoint(typeof (IMapReduceHost), bindingScheme.Binding,
                                    bindingScheme.GetEndpointUri(configuration.HostName));

            host.ConfigureAsSingleton();

            host.EnableMex();

            host.Open();

            return DynamicDisposable.CreateFrom(() => host.Close());

            //TODO: Create an umbrella solution to include all the projects in here plus additional projects with windows services so we can get this stuff running and tested.
            //NOTE: We are not including the windows service project, because these top level projects may be interchangeable, eg. Azure vs. Cmd Line vs. Windows Service etc, and each of them has their drawback. Eg Azure doesn't support msmq.
        }

    }
}
